package link.chengguo.orangemall.ams.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import link.chengguo.orangemall.ams.model.params.AmsAgentParam;
import link.chengguo.orangemall.annotation.SysLog;
import link.chengguo.orangemall.ams.entity.AmsAgent;
import link.chengguo.orangemall.ams.service.IAmsAgentService;
import link.chengguo.orangemall.sys.entity.SysUser;
import link.chengguo.orangemall.sys.service.ISysUserService;
import link.chengguo.orangemall.util.EasyPoiUtils;
import link.chengguo.orangemall.util.LoginThirdUtils;
import link.chengguo.orangemall.util.UserUtils;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author yzb
 * @date 2019-12-21
 * 代理管理
 */
@Slf4j
@RestController
@RequestMapping("/ams/amsAgent")
public class AmsAgentController {

    @Resource
    private IAmsAgentService IAmsAgentService;
    @Resource
    private ISysUserService sysUserService;

    @SysLog(MODULE = "ams", REMARK = "根据条件查询所有代理管理列表")
    @ApiOperation("根据条件查询所有代理管理列表")
    @GetMapping(value = "/list")
    @PreAuthorize("hasAuthority('ams:amsAgent:read')")
    public Object getAmsAgentByPage(AmsAgentParam param,
                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        try {
            Page list=IAmsAgentService.customPageList(pageNum,pageSize,param);
            return new CommonResult().success(list);
//            return new CommonResult().success(IAmsAgentService.page(new Page<AmsAgent>(pageNum, pageSize), new QueryWrapper<>(entity).orderByDesc("id")));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件查询所有代理管理列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "ams", REMARK = "保存代理管理")
    @ApiOperation("保存代理管理")
    @PostMapping(value = "/create")
    @PreAuthorize("hasAuthority('ams:amsAgent:create')")
    public Object saveAmsAgent(@RequestBody AmsAgent entity) {
        try {
            //创建代理账号
            entity.setCreateTime(new Date());
            if (IAmsAgentService.createAgent(entity)){
                return  new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存代理管理：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "sys", REMARK = "代理登录密码重置")
    @ApiOperation("代理登录密码重置")
    @PostMapping(value = "/resetShopPwd")
    public Object resetPwd(@RequestParam("id") Long id) {
        try {
            SysUser user= UserUtils.getCurrentMember();
            if (IAmsAgentService.resetAgentPwd(id)) {
                return new CommonResult().success();
            }else{
                return new CommonResult().failed("密码重置失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("密码重置：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "ams", REMARK = "更新代理管理")
    @ApiOperation("更新代理管理")
    @PostMapping(value = "/update/{id}")
    @PreAuthorize("hasAuthority('ams:amsAgent:update')")
    public Object updateAmsAgent(@RequestBody AmsAgent entity) {
        try {
            entity.setUpdateTime(new Date());
            if (IAmsAgentService.updateAgent(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新代理管理：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "ams", REMARK = "删除代理管理")
    @ApiOperation("删除代理管理")
    @GetMapping(value = "/delete/{id}")
    @PreAuthorize("hasAuthority('ams:amsAgent:delete')")
    public Object deleteAmsAgent(@ApiParam("代理管理id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("代理管理id");
            }
            if (IAmsAgentService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除代理管理：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "ams", REMARK = "给代理管理分配代理管理")
    @ApiOperation("查询代理管理明细")
    @GetMapping(value = "/{id}")
    @PreAuthorize("hasAuthority('ams:amsAgent:read')")
    public Object getAmsAgentById(@ApiParam("代理管理id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("代理管理id");
            }
            AmsAgent coupon = IAmsAgentService.getById(id);
            return new CommonResult().success(coupon);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询代理管理明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }

    }

    @ApiOperation(value = "批量删除代理管理")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.GET)
    @SysLog(MODULE = "ams", REMARK = "批量删除代理管理")
    @PreAuthorize("hasAuthority('ams:amsAgent:delete')")
    public Object deleteBatch(@RequestParam("ids") List
            <Long> ids) {
        boolean count = IAmsAgentService.removeByIds(ids);
        if (count) {
            return new CommonResult().success(count);
        } else {
            return new CommonResult().failed();
        }
    }


    @SysLog(MODULE = "ams", REMARK = "登录代理账号")
    @ApiOperation("登录代理账号")
    @PreAuthorize("hasAuthority('sys:sysUser:loginByAdmin')")
    @PostMapping(value = "/agentLogin")
    public Object agentLogin(@RequestBody AmsAgent entity, HttpServletRequest request) {
        StringBuffer url= request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        String baseUrl=tempContextUrl.substring(0,tempContextUrl.length()-6);
        CommonResult result=null;
        try {
            //组装请求参数
            JSONObject map=new JSONObject();
            map.put("username", entity.getAccount());
            map.put("password", entity.getPassword());
            String params=map.toString();
           result= LoginThirdUtils.loginByAdmin(params,baseUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新代理管理：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return result;
    }

    @SysLog(MODULE = "ams", REMARK = "验证是否有权限登录代理账号")
    @ApiOperation("验证是否有权限登录代理账号")
    @PreAuthorize("hasAuthority('sys:sysUser:loginByAdmin')")
    @PostMapping(value = "/hasAuthorityAdminLogin")
    public boolean hasAuthorityAgentLogin() {
        return true;
    }


    @SysLog(MODULE = "ams", REMARK = "导出社区数据")
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response, AmsAgent entity) {
        // 模拟从数据库获取需要导出的数据
        List<AmsAgent> personList = IAmsAgentService.list(new QueryWrapper<>(entity).orderByDesc("id"));
        // 导出操作
        EasyPoiUtils.exportExcel(personList, "导出社区数据", "社区数据", AmsAgent.class, "导出社区数据.xls", response);

    }

    @SysLog(MODULE = "ams", REMARK = "导入社区数据")
    @PostMapping("/importExcel")
    public void importUsers(@RequestParam MultipartFile file) {
        List<AmsAgent> personList = EasyPoiUtils.importExcel(file, AmsAgent.class);
        IAmsAgentService.saveBatch(personList);
    }

    @SysLog(MODULE = "ams", REMARK = "修改代理密码")
    @ApiOperation("修改代理密码")
    @RequestMapping(value = "/updatePwd",method = {RequestMethod.GET,RequestMethod.POST})
    public Object updatePwd(@RequestBody AmsAgent agent) {
        try {
            SysUser user=UserUtils.getCurrentMember();
            if (IAmsAgentService.updateAgentPwd(user.getId(),agent.getOldPassword(),agent.getPassword())) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改代理密码：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "ams", REMARK = "给代理管理分配代理管理")
    @ApiOperation("查询代理管理明细")
    @GetMapping(value = "/getAgentInfo")
    public Object getAmsAgentById() {
        try {
            SysUser admin=UserUtils.getCurrentMember();
            if (admin==null) {
                return new CommonResult().failed("账号异常");
            }
            AmsAgent parm=new AmsAgent();
            parm.setCityCode(admin.getCityCode());
            AmsAgent coupon = IAmsAgentService.getOne(new QueryWrapper<>(parm));
            return new CommonResult().success(coupon);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询代理管理明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }

    }
}


